﻿using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace shell
{
    public class Shell
    {
        //private PowerShell shell;
        private Runspace runspace;

        //private System.Diagnostics.EventLog logger;

        public Shell(/*System.Diagnostics.EventLog eventLogger, */params string[] config)
        {
            //logger = eventLogger;
            //logger.Source = "Shell";

            PowerShell shell;
            runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
            runspace.Open();

            shell = PowerShell.Create();
            shell.Runspace = this.runspace;
            foreach (var item in config)
            {
                shell.AddScript(item);
            }
            shell.Invoke();
        }

        public Collection<PSObject> run(string cmd, params string[] args)
        {
            PowerShell shell; //
            shell = PowerShell.Create(); //
            shell.Runspace = this.runspace; //

            Collection<PSObject> results = null;
            string parsedCmd = String.Format(cmd, args);

            shell.AddScript(parsedCmd);

            try
            {
               // log(String.Format("[PS] {0}  ", parsedCmd));
                results = shell.Invoke();
               // log(String.Format(" [Done]\n", parsedCmd));
                // Display any non-terminating errors.
                foreach (ErrorRecord error in shell.Streams.Error)
                {
                    // Throw a ShellException, the error string is in this.Message
                    throw new ShellException(String.Format("PowerShell Error: {0} on command \"{1}\"", error, parsedCmd));
                }
            }
            catch (RuntimeException ex)
            {
                throw ex;
            }

            return results;
        }
    }

    public class ShellException : Exception
    {
        // Inherits the Exception class constructor with this.Message as argument
        public ShellException(string Message) : base(Message) { }
    }
}
